package com.htzy.extrace.ui.main;

import java.lang.reflect.Field;
import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.htzy.extrace.loader.UserInfoLoader;
import com.htzy.extrace.misc.model.TransPackage;
import com.htzy.extrace.misc.model.UserInfo;
import com.htzy.extrace.net.IDataAdapter;
import com.htzy.extrace.util.Global;
import com.zxing.activity.CaptureActivity;

public class MyPackageActivity extends ActionBarActivity implements
		IDataAdapter<UserInfo> {
	/**
	 * 可伸展、收缩列表
	 */
	private ExpandableListView expandableListView;
	/**
	 * 一层列表包裹状态信息
	 */
	private ArrayList<String> arrayList_groupData;
	/**
	 * 每层列表中包含的对应状态包裹ID
	 */
	private ArrayList<ArrayList<String>> arrayList_memberData;
	/**
	 * 定义适配器
	 */
	ExAdapter exAdapter;
	/**
	 * 用户三种包裹状态
	 */
	private String[] packageStatus = { "揽收包裹", "派送包裹", "转运包裹" };

	// 揽收包裹
	String receivePackageID;
	// 派送包裹
	String delivePackageID;
	// 转运包裹
	String transPackageID;

	private UserInfo userInfo;
	private SharedPreferences sharedPreferences;
	private static final String CONFIG_USER = Global.CONFIG_USER;

	private int CHOOSE = 2;
	private OnClickEditId onClickEditId = new OnClickEditId(CHOOSE);
	private OnClickDeleteId onClickDeleteId = new OnClickDeleteId(CHOOSE);

	private UserInfoLoader uLoader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.activity_mypackage);
		expandableListView = (ExpandableListView) this
				.findViewById(R.id.expandableListView);
		arrayList_groupData = new ArrayList<String>();
		arrayList_memberData = new ArrayList<ArrayList<String>>();

		userInfo = ExTraceApplication.getUserInfo();

		// 分别得到三种状态包裹的ID
		// 揽收包裹
		receivePackageID = userInfo.getReceivePackageID();
		System.out.println(receivePackageID);

		// 派送包裹
		delivePackageID = userInfo.getDelivePackageID();
		System.out.println(delivePackageID);

		// 转运包裹
		transPackageID = userInfo.getTransPackageID();
		System.out.println(transPackageID);

		for (int i = 0; i < 3; i++) {
			arrayList_groupData.add(packageStatus[i]);
			ArrayList<String> arrayList_memberDataItem = new ArrayList<String>();
			switch (i)
				{
				case 0:
					arrayList_memberDataItem.add(receivePackageID);
					break;
				case 1:
					arrayList_memberDataItem.add(delivePackageID);
					break;
				case 2:
					arrayList_memberDataItem.add(transPackageID);
					break;
				default:
					break;
				}

			arrayList_memberData.add(arrayList_memberDataItem);
		}
		exAdapter = new ExAdapter(this);
		expandableListView.setAdapter(exAdapter);
		// expandableListView.expandGroup(0);//设置第一组张开
		// expandableListView.collapseGroup(0); 将第group组收起
		expandableListView.setGroupIndicator(null);// 除去自带的箭头，自带的箭头在父列表的最左边，不展开向下，展开向上
		// expandableListView.setDivider(null);//这个是设定每个Group之间的分割线。,默认有分割线，设置null没有分割线

		expandableListView.setOnChildClickListener(new OnChildClickListener() {

			@Override
			public boolean onChildClick(ExpandableListView parent, View view,
					int groupPosition, int childPosition, long id) {

				exAdapter.setChildSelection(groupPosition, childPosition);
				exAdapter.notifyDataSetChanged();
				return true;
			}
		});
		// 总是显示overflow按钮，消除部分手机不显示overflow按钮的情况
		setOverflowShowingAlways();
	}

	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 方法说明： Activity启动的时候，系统会调用Activity的onCreateOptionsMenu()方法来取出所有的Action按钮
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// 调用了MenuInflater的inflate()方法来加载menu资源就
		getMenuInflater().inflate(R.menu.mypackage, menu);
		return true;
	}

	/**
	 * 方法说明： 当用户点击Action按钮的时候，系统会调用Activity的onOptionsItemSelected()方法，
	 * 通过方法传入的MenuItem参数，
	 * 我们可以调用它的getItemId()方法和menu资源中的id进行比较，从而辨别出用户点击的是哪一个Action按钮
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		int id = item.getItemId();
		switch (id)
			{
			case R.id.editId: {
				showEditId();
				return true;

			}
			case R.id.deleteId: {
				showDeleteId();
				return true;
			}
			case android.R.id.home: {
				Intent intent = new Intent(this, MainActivity.class);
				startActivity(intent);
				finish();
				return true;
			}
			}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * 显示包裹ID列表
	 */
	private void showEditId() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("修改选项");
		builder.setSingleChoiceItems(packageStatus, CHOOSE, onClickEditId);
		builder.setPositiveButton("确定", onClickEditId);
		builder.setNegativeButton("取消", onClickEditId);
		builder.show();
	}

	/**
	 * 修改ID
	 */
	private class OnClickEditId implements DialogInterface.OnClickListener {
		private int index; // 表示选项的索引

		public OnClickEditId(int index) {
			this.index = index;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			if (which >= 0) {
				// 如果单击的是列表项，将当前列表项的索引保存在index中。
				// 如果想单击列表项后关闭对话框，可在此处调用dialog.cancel()
				// 或是用dialog.dismiss()方法。
				index = which;
				// dialog.cancel();
			} else {
				// 用户单击"确定"按钮
				if (which == DialogInterface.BUTTON_POSITIVE) {
					StartCapture(index);
				} else if (which == DialogInterface.BUTTON_NEGATIVE) {
					// 用户单击"取消"按钮
					// Toast.makeText(MyPackageActivity.this, "您取消了本次操作",
					// Toast.LENGTH_LONG).show();
				}
			}
		}
	}

	/**
	 * 开启相机
	 */
	private void StartCapture(int state) {
		Intent intent = new Intent();
		intent.putExtra("Action", "Captrue");
		intent.setClass(MyPackageActivity.this, CaptureActivity.class);
		startActivityForResult(intent, state);
	}

	/**
	 * 得到扫描后的结果
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (data == null) {
			return;
		}
		switch (requestCode)
			{
			case 0: {
				if (data.hasExtra("result")) {
					receivePackageID = data.getExtras().getString("result");
					System.out.println(receivePackageID);

					userInfo = ExTraceApplication.getUserInfo();
					System.out.println(userInfo.getReceivePackageID());

					userInfo.setReceivePackageID(receivePackageID);
					System.out.println(userInfo.getReceivePackageID());

					uLoader = new UserInfoLoader(this, this);
					if (uLoader.receivePackageEdit(userInfo)) {
						System.out.println(userInfo.getReceivePackageID());

						refresh();
						System.out.println(userInfo.getReceivePackageID());

						Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT)
								.show();
						System.out.println("success!");
					} else {
						Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT)
								.show();
					}
				}
				break;
			}
			case 1: {
				if (data.hasExtra("result")) {
					delivePackageID = data.getExtras().getString("result");
					userInfo.setDelivePackageID(delivePackageID);
					uLoader = new UserInfoLoader(this, this);
					if (uLoader.delivePackageEdit(userInfo)) {
						refresh();
						Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT)
								.show();
					}

				}
				break;
			}
			case 2: {
				if (data.hasExtra("result")) {
					transPackageID = data.getExtras().getString("result");
					userInfo.setTransPackageID(transPackageID);
					uLoader = new UserInfoLoader(this, this);
					if (uLoader.transPackageEdit(userInfo)) {
						refresh();
						Toast.makeText(this, "修改成功！", Toast.LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(this, "修改失败！", Toast.LENGTH_SHORT)
								.show();
					}
				}
				break;
			}
			default:
				break;
			}
	}

	/**
	 * 用户的操作响应之后刷新本页面，更新显示数据
	 */
	private void refresh() {
		Intent intent = new Intent(MyPackageActivity.this,
				MyPackageActivity.class);
		startActivity(intent);
		finish();
	}

	/**
	 * 显示包裹ID列表
	 */

	private void showDeleteId() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("删除选项");
		builder.setSingleChoiceItems(packageStatus, CHOOSE, onClickDeleteId);
		builder.setPositiveButton("确定", onClickDeleteId);
		builder.setNegativeButton("取消", onClickDeleteId);
		builder.show();
	}

	/**
	 * 删除ID
	 */
	private class OnClickDeleteId implements DialogInterface.OnClickListener {
		private int index; // 表示选项的索引

		public OnClickDeleteId(int index) {
			this.index = index;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// which表示单击的按钮索引，所有的选项索引都是大于0，按钮索引都是小于0的。
			if (which >= 0) {
				index = which;
			} else {
				// 用户单击的是【确定】按钮
				if (which == DialogInterface.BUTTON_POSITIVE) {
					deleteId(index);
				} else if (which == DialogInterface.BUTTON_NEGATIVE) {
					// 用户单击的是【取消】按钮
					/*
					 * Toast.makeText(MyPackageActivity.this, "您取消了本次操作",
					 * Toast.LENGTH_LONG).show();
					 */
				}
			}
		}

	}

	/**
	 * 删除包裹ID
	 * 
	 * @param index2
	 */
	private void deleteId(int index2) {
		// 删除包裹暂时不可用，只可以更改
		// 将index2强制修改为3，则不会与下面任意一个选项相匹配，则不会删除包裹
		// index2 = 3;
		switch (index2)
			{
			case 0:
				if (userInfo.getReceivePackageID().length() != 0
						&& !(userInfo.getReceivePackageID()).isEmpty()) {
					userInfo.setReceivePackageID("");
					uLoader = new UserInfoLoader(this, this);

					if (uLoader.receivePackageDelete(userInfo)) {
						// if (userInfo.getReceivePackageID().length() != 0
						// && !(userInfo.getReceivePackageID()).isEmpty()) {
						// Toast.makeText(MyPackageActivity.this, "该包裹未拆，不能删除！",
						// Toast.LENGTH_SHORT).show();
						// } else {
						// userInfo.setReceivePackageID("");
						refresh();
						System.out.println("userinfo");
						Toast.makeText(MyPackageActivity.this, "删除成功！",
								Toast.LENGTH_SHORT).show();
						// }

					} else {
						Toast.makeText(MyPackageActivity.this, "删除失败！",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(MyPackageActivity.this, "该ID已经删除！",
							Toast.LENGTH_SHORT).show();
				}

				break;
			case 1:

				if (userInfo.getDelivePackageID().length() != 0
						&& !(userInfo.getDelivePackageID().isEmpty())) {
					userInfo.setDelivePackageID("");
					uLoader = new UserInfoLoader(this, this);
					if (uLoader.delivePackageDelete(userInfo)) {
						// if (userInfo.getDelivePackageID().length() != 0
						// && !(userInfo.getDelivePackageID().isEmpty())) {
						// Toast.makeText(MyPackageActivity.this, "该包裹未拆，不能删除！",
						// Toast.LENGTH_SHORT).show();
						// } else {
						// userInfo.setDelivePackageID("");
						refresh();
						System.out.println("userinfo");
						Toast.makeText(MyPackageActivity.this, "删除成功！",
								Toast.LENGTH_SHORT).show();
						// }

					} else {
						Toast.makeText(MyPackageActivity.this, "删除失败！",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(MyPackageActivity.this, "该ID已经删除！",
							Toast.LENGTH_SHORT).show();
				}
				break;
			case 2:
				// userInfo = eApplication.getUserInfo();
				if (userInfo.getTransPackageID().length() != 0
						&& !(userInfo.getTransPackageID().isEmpty())) {
					userInfo.setTransPackageID("");
					uLoader = new UserInfoLoader(this, this);

					if (uLoader.transPackageDelete(userInfo)) {
						// if (userInfo.getTransPackageID().length() != 0
						// && !(userInfo.getTransPackageID().isEmpty())) {
						// Toast.makeText(MyPackageActivity.this, "该包裹未拆，不能删除！",
						// Toast.LENGTH_SHORT).show();
						// } else {
						// userInfo.setTransPackageID("");
						refresh();
						System.out.println("userinfo");
						Toast.makeText(MyPackageActivity.this, "删除成功！",
								Toast.LENGTH_SHORT).show();
						// }

					} else {
						Toast.makeText(MyPackageActivity.this, "删除失败！",
								Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(MyPackageActivity.this, "该ID已经删除！",
							Toast.LENGTH_SHORT).show();
				}

				break;
			default:
				break;
			}
	}

	public class ExAdapter extends BaseExpandableListAdapter {
		Context context;
		int selectParentItem = -1;
		int selectChildItem = -1;

		public ExAdapter(Context context) {
			this.context = context;
		}

		public void setChildSelection(int groupPosition, int childPosition) {
			selectParentItem = groupPosition;
			selectChildItem = childPosition;
		}

		@Override
		public Object getChild(int groupPosition, int childPosition) {
			return arrayList_memberData.get(groupPosition).get(childPosition);
		}

		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			View view = convertView;
			/*
			 * Log.i("++++++++++", "groupPosition=" + groupPosition + "," +
			 * "childPosition" + childPosition);
			 */
			if (null == view) {
				// 获取LayoutInflater
				LayoutInflater layoutInflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				// 获取对应的布局
				view = layoutInflater.inflate(R.layout.memberlayout, null);
			}
			TextView textView = (TextView) view
					.findViewById(R.id.memberlayout_textView);
			textView.setText(arrayList_memberData.get(groupPosition).get(
					childPosition));
			if (selectChildItem == childPosition
					&& selectParentItem == groupPosition) {
			}

			return view;
		}

		@Override
		public int getChildrenCount(int groupPosition) {
			return arrayList_memberData.get(groupPosition).size();
		}

		@Override
		public Object getGroup(int groupPosition) {
			return arrayList_groupData.get(groupPosition);
		}

		@Override
		public int getGroupCount() {
			return arrayList_groupData.size();
		}

		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			View view = convertView;
			if (null == view) {
				LayoutInflater layoutInflater = (LayoutInflater) context
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = layoutInflater.inflate(R.layout.grouplayout, null);
			}
			TextView textView = (TextView) view
					.findViewById(R.id.grouplayout_textView);
			textView.setText(arrayList_groupData.get(groupPosition));
			ImageView image = (ImageView) view
					.findViewById(R.id.grouplayout_imageView_tubiao);
			if (isExpanded) {
				image.setBackgroundResource(R.drawable.btn_browser2);
			} else {
				image.setBackgroundResource(R.drawable.btn_browser);
			}
			return view;
		}

		@Override
		public boolean hasStableIds() {
			return true;
		}

		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}

	}

	@Override
	public UserInfo getData() {
		return userInfo;
	}

	@Override
	public void setData(UserInfo data) {
		ExTraceApplication.setUserInfo(userInfo);
	}

	@Override
	public void notifyDataSetChanged() {
		sharedPreferences = getSharedPreferences(CONFIG_USER, 0);
		ExTraceApplication.setUserInfo(getData());
		SharedPreferences.Editor editor = sharedPreferences.edit();
		editor.putInt("UID", userInfo.getUID());
		editor.putString("name", userInfo.getName());
		editor.putInt("URull", userInfo.getURull());
		editor.putString("telCode", userInfo.getTelCode());
		editor.putInt("status", userInfo.getStatus());
		editor.putString("dptID", userInfo.getDptID());
		editor.putString("receivePackageID", userInfo.getReceivePackageID());
		editor.putString("delivePackageID", userInfo.getDelivePackageID());
		editor.putString("transPackageID", userInfo.getTransPackageID());
		editor.commit();
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Intent intent = new Intent(this, MainActivity.class);
			startActivity(intent);
			finish();
		}
		return false;
	}
}
